#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


class ElementPart:

    def __init__(self, element, pname, elementIdList):
        assert (element._esource, element._eindex) in elementIdList

        self._elem = element
        self._pname = pname
        self._elementIdList = elementIdList

        self._dataSrcReal = None
        self._eindexReal = None

    @property
    def pname(self):
        return self._pname

    def get_url(self):
        self._dataSrc.get_element_part_url(self._elem._etype, self._eindex, self._pname)

    def get_local_path(self):
        self._dataSrc.get_element_part_cache_local_path(self._elem._etype, self._eindex, self._pname)

    def get_cache_last_update_time(self):
        self._dataSrc.get_element_part_cache_last_update_time(self._elem._etype, self._eindex, self._pname)

    @property
    def _dataSrc(self):
        if self._dataSrcReal is None:
            self.__ensureDataSrc()
        return self._dataSrcReal

    @property
    def _eindex(self):
        if self._eindexReal is None:
            self.__ensureDataSrc()
        return self._eindexReal

    def __ensureDataSrc(self):
        # data source which do cache takes priority
        for esource, eindex in self._elementIdList:
            dataSrc = self._elem._library._dataSrcDict[esource]
            ret = dataSrc.get_element_part_cache_last_update_time(self._elem._etype, eindex, self._pname)
            if ret is not None:
                self._dataSrcReal = dataSrc
                self._eindexReal = eindex
                return

        # simply use the first
        self._dataSrcReal, self._eindexReal = self._elementIdList[0]
        self._dataSrcReal = self._elem._library._dataSrcDict[self._dataSrcReal]
